let app = getApp();
import Toast from '@vant/weapp/toast/toast';
import areaList from '../../utils/area';

Page({
  data: {
    // 表单数据
    aid: '',
    name: '',
    tel: '',
    province: '',
    city: '',
    county: '',
    addressDetail: '',
    areaCode: '',
    postalCode: '',
    isDefault: false,
    
    // 错误状态
    nameError: false,
    telError: false,
    areaError: false,
    addressDetailError: false,
    postalCodeError: false,
    
    // 地区选择相关
    areaList,
    showAreaPopup: false,
    areaText: '',
    
    // 其他
    token: '',
    isEdit: false  // 是否是编辑模式
  },

  onLoad(options) {
    // 获取token
    wx.getStorage({
      key: "_token",
      success: (res) => {
        this.setData({
          token: res.data
        });
        
        // 如果有aid参数，说明是编辑模式
        if (options.aid) {
          this.setData({
            isEdit: true,
            aid: options.aid
          });
          wx.setNavigationBarTitle({
            title: '编辑地址'
          });
          this.loadAddressDetail(options.aid);
        } else {
          wx.setNavigationBarTitle({
            title: '新增地址'
          });
        }
      },
      fail: () => {
        wx.redirectTo({
          url: '/pages/login/login',
        });
      }
    });
  },

  // 加载地址详情
  loadAddressDetail(aid) {
    wx.showLoading({
      title: '加载中...',
    });

    wx.request({
      url: 'https://kf.webxyq.com/findAddressByAid',
      method: 'GET',
      data: {
        appkey: app.globalData.appkey,
        tokenString: this.data.token,
        aid: aid
      },
      success: (res) => {
        if (res.data && res.data.status === 'success' && res.data.result) {
          const address = res.data.result;
          this.setData({
            name: address.name,
            tel: address.tel,
            province: address.province,
            city: address.city,
            county: address.county,
            addressDetail: address.addressDetail,
            areaCode: address.areaCode,
            postalCode: address.postalCode,
            isDefault: address.isDefault == 1,
            areaText: `${address.province} ${address.city} ${address.county}`
          });
        } else {
          wx.showToast({
            title: '获取地址详情失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 表单字段变更处理函数
  onNameChange(e) {
    this.setData({
      name: e.detail,
      nameError: e.detail.trim() === ''
    });
  },

  onTelChange(e) {
    const telReg = /^1[3-9]\d{9}$/;
    this.setData({
      tel: e.detail,
      telError: e.detail && !telReg.test(e.detail)
    });
  },

  onAddressDetailChange(e) {
    this.setData({
      addressDetail: e.detail,
      addressDetailError: e.detail.trim() === ''
    });
  },

  onPostalCodeChange(e) {
    const postalReg = /^[1-9]\d{5}$/;
    this.setData({
      postalCode: e.detail,
      postalCodeError: e.detail && !postalReg.test(e.detail)
    });
  },

  onDefaultChange(e) {
    this.setData({
      isDefault: e.detail
    });
  },

  // 地区选择相关
  showAreaPopup() {
    this.setData({
      showAreaPopup: true
    });
  },

  onCloseAreaPopup() {
    this.setData({
      showAreaPopup: false
    });
  },

  onConfirmArea(e) {
    const values = e.detail.values;
    this.setData({
      province: values[0].name,
      city: values[1].name,
      county: values[2].name,
      areaCode: values[2].code,
      areaText: `${values[0].name} ${values[1].name} ${values[2].name}`,
      showAreaPopup: false,
      areaError: false
    });
  },

  // 表单验证
  validateForm() {
    const telReg = /^1[3-9]\d{9}$/;
    const postalReg = /^[1-9]\d{5}$/;
    
    const nameError = this.data.name.trim() === '';
    const telError = !telReg.test(this.data.tel);
    const areaError = !this.data.areaCode;
    const addressDetailError = this.data.addressDetail.trim() === '';
    const postalCodeError = this.data.postalCode && !postalReg.test(this.data.postalCode);
    
    this.setData({
      nameError,
      telError,
      areaError,
      addressDetailError,
      postalCodeError
    });
    
    return !nameError && !telError && !areaError && !addressDetailError && !postalCodeError;
  },

  // 保存地址
  onSave() {
    if (!this.validateForm()) {
      Toast('请填写正确的信息');
      return;
    }
    
    wx.showLoading({
      title: '保存中...',
    });
    
    const url = this.data.isEdit ? 'https://kf.webxyq.com/editAddress' : 'https://kf.webxyq.com/addAddress';
    const data = {
      appkey: app.globalData.appkey,
      tokenString: this.data.token,
      name: this.data.name,
      tel: this.data.tel,
      province: this.data.province,
      city: this.data.city,
      county: this.data.county,
      addressDetail: this.data.addressDetail,
      areaCode: this.data.areaCode,
      postalCode: this.data.postalCode || '',
      isDefault: this.data.isDefault ? 1 : 0
    };
    
    // 编辑模式需要添加aid参数
    if (this.data.isEdit) {
      data.aid = this.data.aid;
    }
    
    wx.request({
      url: url,
      method: 'POST',
      data: data,
      success: (res) => {
        if (res.data && res.data.status === 'success') {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        } else {
          wx.showToast({
            title: res.data.msg || '保存失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 删除地址
  onDelete() {
    wx.showModal({
      title: '提示',
      content: '确定要删除这个地址吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...',
          });
          
          wx.request({
            url: 'https://kf.webxyq.com/deleteAddress',
            method: 'POST',
            data: {
              appkey: app.globalData.appkey,
              tokenString: this.data.token,
              aid: this.data.aid
            },
            success: (res) => {
              if (res.data && res.data.status === 'success') {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
                setTimeout(() => {
                  wx.navigateBack();
                }, 1500);
              } else {
                wx.showToast({
                  title: '删除失败',
                  icon: 'none'
                });
              }
            },
            fail: () => {
              wx.showToast({
                title: '网络错误，请重试',
                icon: 'none'
              });
            },
            complete: () => {
              wx.hideLoading();
            }
          });
        }
      }
    });
  }
});